package cValidator

import (
	"reflect"
	"sync"

	"github.com/go-playground/validator/v10"
)

type ValidatorContainer struct {
	lock      sync.RWMutex
	instances map[string]any
}

func (i *ValidatorContainer) Save(instance any) bool {
	i.lock.Lock()
	defer i.lock.Unlock()

	app, name := instance.(ValidatorInterface).ValidatorName()
	index := app + "." + name
	i.instances[index] = instance

	return true
}

func (i *ValidatorContainer) Get(name string) any {
	i.lock.RLock()
	defer i.lock.RUnlock()

	return i.instances[name]
}

func (i *ValidatorContainer) Remove(name string) bool {
	i.lock.Lock()
	defer i.lock.Unlock()

	delete(i.instances, name)

	return true
}

func (i *ValidatorContainer) Is(instance any) bool {
	return reflect.TypeOf(instance).Implements(reflect.TypeOf((*ValidatorInterface)(nil)).Elem())
}

func (i *ValidatorContainer) Range(f func(instance any)) {
	i.lock.RLock()
	defer i.lock.RUnlock()

	for _, item := range i.instances {
		f(item)
	}
}

var container = &ValidatorContainer{
	lock:      sync.RWMutex{},
	instances: make(map[string]any),
}

var Verifier *validator.Validate
